/**
 * 国际化平台客户端 - JavaScript 版本
 * 用于从国际化平台获取词条
 */

export class I18nPlatformClient {
  constructor(config) {
    this.config = {
      autoRefresh: false,
      refreshInterval: 10 * 60 * 1000, // 默认10分钟
      namespace: '',
      version: '',
      ...config
    };
    
    this.refreshTimer = null;
    
    if (this.config.autoRefresh) {
      this.startAutoRefresh();
    }
  }

  /**
   * 从国际化平台获取词条
   */
  async fetchTranslations(locale) {
    const targetLocale = locale || this.config.defaultLocale;

    // 构建请求URL
    const url = new URL(
      `${this.config.platformUrl}/api/v1/products/${this.config.productCode}/translations`
    );
    url.searchParams.set('locale', targetLocale);
    if (this.config.namespace) {
      url.searchParams.set('namespace', this.config.namespace);
    }
    if (this.config.version) {
      url.searchParams.set('version', this.config.version);
    }

    try {
      const response = await fetch(url.toString(), {
        headers: {
          'Accept': 'application/json',
          'Accept-Language': targetLocale
        }
      });

      if (!response.ok) {
        throw new Error(`获取词条失败: ${response.statusText}`);
      }

      const result = await response.json();
      const translations = result.data || {};

      return translations;
    } catch (error) {
      console.error('获取词条失败:', error);
      throw error;
    }
  }



  /**
   * 开始自动刷新
   */
  startAutoRefresh() {
    this.refreshTimer = setInterval(() => {
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('i18n-refresh'));
      }
    }, this.config.refreshInterval);
  }

  /**
   * 停止自动刷新
   */
  stopAutoRefresh() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
      this.refreshTimer = null;
    }
  }

  /**
   * 销毁客户端
   */
  destroy() {
    this.stopAutoRefresh();
  }
}


